<?php

namespace app\admin\command;

use app\admin\model\ActiveUserSta;
use app\admin\model\DeviceBind;
use app\admin\model\DeviceImei;
use app\admin\model\DeviceLocation;
use app\admin\model\User;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;


class CalcActiveUser extends Command
{
    protected function configure()
    {
        $this->setName('CalcActiveUser')
            ->setDescription('计算活跃用户');
    }

    protected function execute(Input $input, Output $output)
    {

        $output->writeln('开始执行 ' . date('Y-m-d H:i:s'));

        foreach ([1, 2, 3, 4] as $type) {
            $where = [];
            $where['type'] = $type;
            $where['year'] = date('Y');
            switch ($type) {
                case 1://日
                    $where['day'] = date('d');
                    $where['month'] = date('m');
                    $time = strtotime('today');
                    break;
                case 2://周
                    $where['week'] = date('W');
                    $time = strtotime('this week monday');
                    break;
                case 3://月
                    $where['month'] = date('m');
                    $time = strtotime(date('Y-m-01'));
                    break;
                case 4://年
                    $time = strtotime(date('Y-01-01'));
                    break;
            }
            $row = ActiveUserSta::where($where)->findOrEmpty();

            if ($row->isEmpty()) {
                $row->isUpdate(false)->save([
                    'year' => date('Y'),
                    'month' => date('m'),
                    'day' => date('d'),
                    'week' => date('W'),
                    'type' => $type,
                ]);
            }

            $user_num = User::where(['user_type' => 1, 'mark' => 1])->count();
            $active_user_num = User::where(['user_type' => 1, 'mark' => 1, 'login_time' => ['>=', $time]])->count();

            $imei_list = DeviceBind::column('DISTINCT imei');
            $terminal_num = count($imei_list);
            $active_terminal_num = DeviceLocation::where('create_time', '>=', $time)->whereIn('imei', $imei_list)->group('imei')->count();


            $row->save(compact('user_num', 'active_user_num', 'terminal_num', 'active_terminal_num'));
        }
        $output->writeln('执行结束 ' . date('Y-m-d H:i:s'));
    }

}